<?php

namespace addons\sum\controller;

use addons\sum\controller\Common;
use addons\sum\service\Wallet as WalletService;
use app\admin\model\sum\Card as CardModel;
use app\admin\model\sum\CardLog as CardLogModel;
use think\Db;

class Card extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $this->error(__('No Results were found'));
    }

    public function mycard()
    {
        $list_rows = $this->request->param('list_rows', 10);
        $user = auth_user();
        $records=CardLogModel::where('user_id',$user['id'])->paginate($list_rows);
        $this->success(__('Success'),$records);
    }

    public function draw()
    {
        $user = auth_user();
        //抽卡消耗积分
        $score=sum_config('shop.basic.card_score',false);
        if(!$score){
            $score=10;
        }
        $card= Db::transaction(function () use ($score,$user) {
            // 扣除用户积分
            WalletService::change($user, 'score', -$score, 'card_pay');
            // 随机获取一张卡片
            $card=CardModel::where('status','normal')->orderRaw('RAND()')->find();
            if(!$card){
                $this->error(__('No Results were found'));
            }
            //添加抽卡记录
            $card_log=new CardLogModel();
            $card_log->user_id=$user['id'];
            $card_log->card_id=$card['id'];
            $card_log->image=$card['image'];
            $card_log->save();
            return $card;
        });
        $this->success(__('Success'),$card);
    }



}
